package com.example.hospitalapp;

import android.os.Bundle;
import android.util.Log;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;

public class DoctorMedicalRecordActivity extends AppCompatActivity {

    private ListView listViewMedicalRecords;
    private ArrayList<MedicalRecord> medicalRecords;
    private ArrayList<Patient> patients;
    private DoctorMedicalRecordActivityAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d("DoctorMedicalRecord", "onCreate called");
        setContentView(R.layout.activity_doctor_medical_record);

        listViewMedicalRecords = findViewById(R.id.listViewMedicalRecords);
        medicalRecords = new ArrayList<>();
        patients = new ArrayList<>();

        // 获取传递过来的医生信息
        Doctor doctor = (Doctor) getIntent().getSerializableExtra("doctor_info");

        int doctorId = getIntent().getIntExtra("doctorId", -1);
        Log.d("DoctorMedicalRecord", "doctorId: " + doctorId);

        if (doctorId == -1) {
            Log.e("DoctorMedicalRecord", "Error: doctorId not passed correctly.");
        }

            queryMedicalRecords(doctorId);

    }

    // 查询该医生的所有病历
    private void queryMedicalRecords(int doctorId) {
        JSONObject params = new JSONObject();
        try {
            params.put("doctorId", doctorId); // 传递医生 ID
        } catch (Exception e) {
            e.printStackTrace();
        }
        Log.d("DoctorMedicalRecord", "Sending request with doctorId: " + doctorId);

        ApiClient apiClient = new ApiClient(DoctorMedicalRecordActivity.this);
        apiClient.postRequest("http://zhsj.autumnclouds.cn/medicalrecord/query", params, new ApiClient.VolleyCallback() {
            @Override
            public void onSuccess(JSONObject response) {
                try {
                    int code = response.getInt("code");
                    if (code == 200) {
                        Log.d("MedicalRecord", "Response Data: " + response.toString());
                        // 获取病历数据
                        JSONArray medicalRecordArray = response.getJSONArray("data");
                        if (medicalRecordArray.length() == 0) {
                            Log.d("DoctorMedicalRecord", "No medical records found for this doctor.");
                        }else {
                            Log.d("DoctorMedicalRecord", "Found " + medicalRecordArray.length() + " medical records.");
                        }
                        for (int i = 0; i < medicalRecordArray.length(); i++) {
                            JSONObject recordData = medicalRecordArray.getJSONObject(i);

                            // 创建 MedicalRecord 对象
                            MedicalRecord medicalRecord = new MedicalRecord(
                                    recordData.getInt("recordId"),  // 获取记录ID
                                    recordData.getInt("patientId"),  // 获取病人ID
                                    recordData.getInt("doctorId"),   // 获取医生ID
                                    recordData.getString("visitDate"), // 获取就诊日期
                                    recordData.getString("treatment"), // 获取治疗方案
                                    recordData.getString("type"), // 获取病历类型
                                    recordData.getString("allergicHistory"), // 获取过敏史
                                    recordData.getString("illnessHistory"), // 获取疾病史
                                    Integer.parseInt(recordData.getString("isComplete")), // 将isComplete从String转换为int
                                    recordData.getString("onsetDate"), // 获取发病日期
                                    recordData.getString("diagnosis") // 获取诊断
                            );

                            medicalRecords.add(medicalRecord);  // 将病历信息添加到列表

                            // 查询病人信息并更新

                        }

                        // 设置适配器
                        if (medicalRecords != null && !medicalRecords.isEmpty()) {
                            Log.d("DoctorMedicalRecord", "Binding medical records to ListView.");
                            DoctorMedicalRecordActivityAdapter adapter = new DoctorMedicalRecordActivityAdapter(DoctorMedicalRecordActivity.this, medicalRecords, patients);
                            listViewMedicalRecords.setAdapter(adapter);
                        } else {
                            Log.d("DoctorMedicalRecord", "No medical records to display.");
                        }



                    } else {
                        Toast.makeText(DoctorMedicalRecordActivity.this, "查询病历失败", Toast.LENGTH_SHORT).show();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(DoctorMedicalRecordActivity.this, "查询病历失败", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(String error) {
                Toast.makeText(DoctorMedicalRecordActivity.this, "查询病历失败", Toast.LENGTH_SHORT).show();
            }
        });
    }

    // 查询病人信息
    private void queryPatientInfo(int patientId) {
        JSONObject params = new JSONObject();
        try {
            params.put("patientId", patientId);  // 传递病人 ID
        } catch (Exception e) {
            e.printStackTrace();
        }

        ApiClient apiClient = new ApiClient(DoctorMedicalRecordActivity.this);
        apiClient.getRequest("http://zhsj.autumnclouds.cn/patient/" + patientId, new ApiClient.VolleyCallback() {
            @Override
            public void onSuccess(JSONObject response) {
                try {
                    int code = response.getInt("code");
                    if (code == 200) {
                        Log.d("MedicalRecord", "Response Data: " + response.toString());
                        // 获取病人信息
                        JSONObject patientData = response.getJSONObject("data");

                        // 创建病人对象
                        Patient patient = new Patient(
                                patientData.getInt("patientId"),
                                patientData.getString("name"),
                                patientData.getString("gender"),
                                patientData.getString("birthDate"),
                                patientData.getString("phoneNumber"),
                                patientData.getString("email"),
                                patientData.getString("address"),
                                patientData.getString("password")
                        );

                        // 将病人信息添加到 patients 列表
                        patients.add(patient);

                        // 刷新适配器
                        adapter.notifyDataSetChanged();
                    } else {
                        Toast.makeText(DoctorMedicalRecordActivity.this, "查询病人信息失败", Toast.LENGTH_SHORT).show();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(DoctorMedicalRecordActivity.this, "查询病人信息失败", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(String error) {
                Toast.makeText(DoctorMedicalRecordActivity.this, "查询病人信息失败", Toast.LENGTH_SHORT).show();
            }
        });
    }
}
